﻿package com.googlecode.astoolkit.modules.content.model {


	import com.googlecode.astoolkit.modules.content.ContentEvents;
	import com.googlecode.astoolkit.modules.content.iterators.ArrayIterator;
	import com.googlecode.astoolkit.modules.content.iterators.IIterator;
	import com.googlecode.astoolkit.modules.content.iterators.NullIterator;
	import com.googlecode.astoolkit.utils.Sitemap;
	import com.googlecode.astoolkit.vo.ParamsObject;
	import com.googlecode.astoolkit.vo.PathObject;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class ContentModel extends EventDispatcher {

		private static var _instance:ContentModel;

		private var _path:String;
		private var _pathNames:Array;
		private var _pathIds:IIterator;
		private var _params:ParamsObject;

		public function ContentModel(singletonenforcer:SingletonEnforcer) {
			super();

			if (singletonenforcer == null) {
				throw new Error("ContentModel es un Singleton. Para acceder a una instancia hacedlo mediante ContentModel.getInstance()");
				return ;
			}
			_path = "";
			_pathNames = new Array();
			_pathIds = new NullIterator();
			_params = new ParamsObject();
		}

		public static function getInstance():ContentModel {
			if (!_instance) {
				_instance = new ContentModel(new SingletonEnforcer());
			}

			return _instance;
		}

		// Cada vez que la url cambia, se lo comunico a las vistas para que se actualicen
		// La primera vez, redirecciono a la seccion inicial que ponga en el xml
		public function onPathChanged(pathObj:PathObject):void {
			_params = pathObj.params;
			_pathNames = pathObj.pathNames;
			_path = pathObj.path;
			_pathIds = new ArrayIterator(Sitemap.getIdsArrayByPath(pathObj.path));
			// Difundo el evento PATH_CHANGED para que todas las vistas se enteren
			dispatchEvent(new Event(ContentEvents.PATH_CHANGED));
		}

		public function dispatchParamsChangedEvent(params:ParamsObject):void {
			_params = params;
			dispatchEvent(new Event(ContentEvents.PARAMS_CHANGED));
		}
		
		// Getter de _path
		public function get path():String {
			return _path;
		}

		// Getter Setter de _pathNames
		public function get pathNames():Array {
			return _pathNames;
		}

		public function get pathIds():IIterator {
			return _pathIds;
		}

		// Getter y Setter de _params
		public function get params():ParamsObject {
			return _params;
		}


	}
}

class SingletonEnforcer {}
